package com.hyd.demo;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

public class WaitNotify {
    private static Queue<Integer> queue = new LinkedList<>();
    private static final int LENGTH = 5;
    private static Random random = new Random();
    private static Object lock = new Object();

    public static void main(String[] args) {
        Thread threadInsert = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    queueInsert();
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread threadRemove = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    queueRemove();
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        threadInsert.start();
        threadRemove.start();
    }

    public static void queueInsert() {
        synchronized (lock) {
            while (queue.size() >= LENGTH) {
                try {
                    System.out.println("队列已满，等待空间");
                    lock.wait(); 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            int index = random.nextInt(10);
            queue.offer(index);
            System.out.println("队列添加数据:" + index);
            lock.notifyAll(); 
        }
    }

    public static void queueRemove() {
        synchronized (lock) {
            while (queue.isEmpty()) {
                try {
                    System.out.println("队列为空，等待数据");
                    lock.wait(); 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            int index = queue.remove();
            System.out.println(index + "被移除");
            lock.notifyAll(); 
        }
    }
}
